#include <stdio.h>
#include <stdlib.h>

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define STACK_INCREATMENT 10
#define MAX_SIZE 100
typedef int Status;
typedef int SElemType;

typedef struct SqStack // 课本的栈底不存数据
{
    SElemType *base;
    SElemType *top;
    int stacksize;
} SqStack;

Status InitStack(SqStack *stack)
{
    stack->base = (SElemType *)malloc(sizeof(SElemType) * MAX_SIZE);
    stack->stacksize = MAX_SIZE;
    stack->top = stack->base;
    return OK;
}

Status push(SqStack *stack, SElemType e)
{
    stack->top++; // 栈底不放
    *stack->top = e;
}

Status clear_SqStack(SqStack *stack)
{
    while (stack->top != stack->base)
    {
        printf("%d ", *(stack->top));
        stack->top--;
    }
    printf("\n");
    return OK;
}

Status is_empty(SqStack *stack)
{
    if (stack->top == stack->base)
    {
        return TRUE;
    }
    return FALSE;
}

Status Get_top(SqStack *stack, SElemType *e)
{
    if (stack->top == stack->base)
    {
        return ERROR;
    }
    else
    {
        *e = *stack->top;
    }
    return OK;
}

int Get_length(SqStack *stack)
{
    return stack->top - stack->base;
}

Status pop(SqStack *stack, SElemType *e)
{
    if (stack->top == stack->base)
    {
        return ERROR;
    }
    *e = *stack->top;
    stack->top--;
    return OK;
}

int main()
{
    // 初始化一个栈
    SqStack *s = (SqStack *)malloc(sizeof(SqStack));
    InitStack(s);

    // 压栈赋值
    for (int i = 0; i < 5; i++)
    {
        push(s, i);
    }
    printf("输出并清空栈:");
    clear_SqStack(s); // clear肩负输出的作用

    printf("s是否为空:%d\n", is_empty(s)); // 判断栈是否为空
    printf("------------------------重新压栈------------------------\n");
    printf("------------------------依次压入6,5,4,3,2,1-------------\n");

    for (int i = 6; i >= 1; i--)
    {
        push(s, i);
    }

    // 判断栈是否为空
    printf("\ns是否为空:%d\n", is_empty(s));

    // 获取栈顶元素
    SElemType *top = (SElemType *)malloc(sizeof(SElemType));
    *top = -1;
    Get_top(s, top);
    printf("\n栈顶元素为:%d\n", *top);

    // 获取栈内元素个数
    int length = Get_length(s);
    printf("\n元素个数为%d\n", length);

    printf("------------------------不断pop直到清空栈------------------------\n");
    SElemType *e = (SElemType *)malloc(sizeof(SElemType));
    int count = 1;
    while (pop(s, e) != ERROR)
    {
        printf("第%d次pop的值为:%d\n",count, *e);
        count++;
    }
}